package com.atqh.srrt.chicken.mq;

import com.alibaba.fastjson.JSON;
import com.atqh.srrt.chicken.service.ArticleService;
import com.atqh.srrt.chicken.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.TextMessage;
import java.time.Duration;
import java.util.Set;

/**
 * @作者：大叔azhe
 * @api：详细描述
 * @创建时间：21:36 2023/1/2
 */
@Component
@Slf4j
public class ActiveMqListenser {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ArticleService articleService;

    @JmsListener(destination = "${mytopic}")
    public void receive(TextMessage textMessage) throws Exception {
        System.out.println("消费者受到的需要更新缓存的文章ID：" + textMessage.getText());
        String params = DigestUtils.md5Hex(textMessage.getText());
        String rediskey = "ArticleDetial::ArticleController::findArticleById::" + params;
        Result articleById = articleService.findArticleById(Long.parseLong(textMessage.getText()));
        redisTemplate.opsForValue().set(rediskey, JSON.toJSONString(articleById), Duration.ofMillis(5 * 60 * 1000));
        log.info("更新了缓存:{}", rediskey);

        Set<String> keys = redisTemplate.keys("listArticle::ArticleController::listArticle::*");
        keys.forEach(
                key -> {
                    redisTemplate.delete(key);
                    log.info("删除了文章列表缓存:{}", key);
                }
        );
    }
}
